package com.yorick.netty.utils;

import java.io.IOException;
import java.io.InputStream;

/**
 *  Socket数据解析所需工具类
 */
public class ServerUtil {

    public static byte[] decode(InputStream in, int start, int length) throws IOException {
        byte[] buf = new byte[length];
        int len=0;
        int curlen=0;
        while (true){
            len=(in.read(buf,curlen,length - curlen));
            curlen += len;
            if(curlen >= length)
                return buf;
        }
    }


    public static int bytes2IntBig(byte[] bytes )
    {
        int int1=bytes[3]&0xff;
        int int2=(bytes[2]&0xff)<<8;
        int int3=(bytes[1]&0xff)<<16;
        int int4=(bytes[0]&0xff)<<24;
        return int1|int2|int3|int4;
    }

    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }

    public static short byte2short(byte[] bytes){
        byte high = bytes[0];
        byte low = bytes[1];
        short z = (short)(((high & 0x00FF) << 8) | (0x00FF & low));
        return z;

    }
    public static byte[] short2Byte(short x){
        byte high = (byte) (0x00FF & (x>>8));//定义第一个byte
        byte low = (byte) (0x00FF & x);//定义第二个byte
        byte[] bytes = new byte[2];
        bytes[0] = high;
        bytes[1] = low;
        return bytes;
    }

}
